package com.func.domain.activity.service.quota.rule.impl;

import com.func.domain.activity.model.entity.ActivityCountEntity;
import com.func.domain.activity.model.entity.ActivityEntity;
import com.func.domain.activity.model.entity.ActivitySkuEntity;
import com.func.domain.activity.model.valobj.ActivitySkuStockKeyVO;
import com.func.domain.activity.repository.IActivityRepository;
import com.func.domain.activity.service.armory.IActivityDispatch;
import com.func.domain.activity.service.quota.rule.AbstractActionChain;
import com.func.types.enums.ResponseCode;
import com.func.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * <p>
 * ActivitySkuStockActionChain
 * </p>
 *
 * @author Simon
 * @version 2025.03.12.1.0.0
 * @description 活动sku库存校验
 * @since 2025-03-12
 */

@Slf4j
@Component("activity_sku_stock_action")
public class ActivitySkuStockActionChain extends AbstractActionChain {
    @Resource
    private IActivityRepository activityRepository;
    @Resource
    private IActivityDispatch activityDispatch;

    @Override
    public boolean action(ActivitySkuEntity activitySkuEntity, ActivityEntity activityEntity, ActivityCountEntity activityCountEntity) {
        log.info("活动责任链-商品库存处理 [有效期, 状态, 库存(sku)] 开始, sku :{} activityId: {}", activitySkuEntity.getSku(), activitySkuEntity.getActivityId());
        // 扣减库存
        boolean status = activityDispatch.subtractionActivitySkuStock(activitySkuEntity.getSku(), activityEntity.getEndDateTime());
        // true: 扣减成功
        if(status) {
            log.info("活动责任链-商品库存处理 [有效期, 状态, 库存(sku)] 成功. sku: {} activityId: {}", activitySkuEntity.getSku(), activitySkuEntity.getActivityId());

            // 写入延迟队列, 延迟消费更新库存记录
            activityRepository.activitySkuStockConsumeSendQueue(ActivitySkuStockKeyVO.builder()
                    .sku(activitySkuEntity.getSku())
                    .activityId(activityEntity.getActivityId())
                    .build());

            log.info("活动责任链-商品库存处理 [有效期, 状态, 库存(sku)] 结束, sku :{} activityId: {}", activitySkuEntity.getSku(), activitySkuEntity.getActivityId());
            return true;
        }

        throw new AppException(ResponseCode.ACTIVITY_SKU_STOCK_ERROR.getCode(), ResponseCode.ACTIVITY_SKU_STOCK_ERROR.getInfo());
    }
}
